/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.mem.impl;

import java.io.Closeable;
import java.nio.BufferOverflowException;

import org.sabayframework.mem.BigBuffer;

/**
 * Interface defining interaction with {@link BigBuffer}
 */
public interface BigBufferAllocator
    extends Closeable
{
    
    /**
     * Returns the given {@link BigBuffer} making it available for a future usage. Returning twice a {@link BigBuffer} won't throw an exception. 
     * @param buffer : the {@link BigBuffer} to return
     */
    void free( final BigBuffer buffer );
    
    /**
     * Allocates and returns a {@link BigBuffer} with {@link BigBuffer#limit()} set to the given size.
     * When the allocation fails, it returns either null or throws an {@link BufferOverflowException}, depending on the implementation. 
     * @param size : the size in byte to allocate
     * @return a {@link BigBuffer} of the given size, or either return null or throw an {@link BufferOverflowException} when the allocation fails.
     */
    BigBuffer allocate(final long size);
    
    /**
     * Duplicates content of given buffer and returns new  {@link BigBuffer}.
     * Uses {@link #allocate(long)} method. 
     * This method allocates n = data.remaining() bytes for new buffer and copies 
     * n bytes from current position in data buffer to new buffer starting with 0 position. 
     * @param data data buffer to duplicate
     * @return a {@link BigBuffer}, or either return null or throw an {@link BufferOverflowException} when the allocation fails.
     * */
    BigBuffer allocate( BigBuffer data );
    
    /**
     * Clear all allocated {@link BigBuffer}, resulting in a empty and ready to deserve {@link BigBufferAllocator}
     */
    void clear();
    
    /**
     * @return the internal total size that can be allocated 
     */
    long getCapacity();
        
}